iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 5
0
IoT

簡簡單單的MQTT入門系列 第 5

Ardunio

  • 分享至 

  • xImage
  •  

這是我使用聯發科技LinkIt™ 7697去訂閱、發佈MQTT訊息,連接WIFI是直接使用Ardunio的範例修改,連接MQTT是使用MQTT教學(六):使用PubSubClient程式庫開發Arduino MQTT應用的範例修改。

發佈

#include <LWiFi.h>
#include <PubSubClient.h>

char ssid[] = "";     //  your network SSID (name)
char pass[] = "1234567890";  // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
const char* mqttServer = "192.168.43.141";  // MQTT伺服器位址
const char* clientID = "test";      // 用戶端ID,隨意設定。
const char* mqttUserName = "";  // mqtt使用者名稱
const char* mqttPwd = "";  // MQTT密碼
const char* topic = "temperature/Wuling";
unsigned long prevMillis = 0;  // 暫存經過時間(毫秒)
const long interval = 20000;  // 上傳資料的間隔時間,20秒。
String msgStr = "";      // 暫存MQTT訊息字串

WiFiClient espClient;
PubSubClient client(espClient);


void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  setup_wifi();

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");

  client.setServer(mqttServer, 1883);
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect(clientID, mqttUserName, mqttPwd)) {
      Serial.println("MQTT connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);  // 等5秒之後再重試
    }
  }
}

void loop() {
  // check the network connection once every 10 seconds:
  delay(10000);

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  // 等待20秒
  if (millis() - prevMillis > interval) {
    prevMillis = millis();

    // 組合MQTT訊息
    msgStr = msgStr + (random(0, 300) / 10.0);

    // 宣告字元陣列
    byte arrSize = msgStr.length() + 1;
    char msg[arrSize];

    Serial.print("Publish message: ");
    Serial.println(msgStr);
    msgStr.toCharArray(msg, arrSize); // 把String字串轉換成字元陣列格式
    client.publish(topic, msg);       // 發布MQTT主題與訊息
    msgStr = "";
  }
}

void setup_wifi() {
  delay(10);

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("");
  Serial.println("WiFi connected");
}

訂閱

#include <LWiFi.h>
#include <PubSubClient.h>

char ssid[] = "☆";     //  your network SSID (name)
char pass[] = "1234567890";  // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
const char* mqttServer = "192.168.43.141";  // MQTT伺服器位址
const char* clientID = "test";      // 用戶端ID,隨意設定。
const char* mqttUserName = "";  // 使用者名稱,隨意設定。
const char* mqttPwd = "";  // MQTT密碼
const char* topic = "temperature/Wuling";
unsigned long prevMillis = 0;  // 暫存經過時間(毫秒)
const long interval = 20000;  // 上傳資料的間隔時間,20秒。
String msgStr = "";      // 暫存MQTT訊息字串

WiFiClient espClient;
PubSubClient client(espClient);


void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  setup_wifi();


  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");

  client.setServer(mqttServer, 1883);
  client.setCallback(callback);
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect(mqttServer, mqttUserName, mqttPwd )) {
      Serial.println("connected");  
    } else {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
 
    }
  }
 
  client.subscribe(topic);
}


void loop() {
  client.loop();
}

void setup_wifi() {
  delay(10);

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("");
  Serial.println("WiFi connected");
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

}

上一篇
很棒的教學資料
下一篇
Javascript
系列文
簡簡單單的MQTT入門23
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言